import json
from django.conf import settings
from django.contrib.auth import authenticate
import jwt
import time

from django.http import JsonResponse

from user.models import UserProfile


def tokens(request):
    if request.method != "POST":
        return JsonResponse({"code": 10200, "error": "请求错误"})
    data = json.loads(request.body)
    username = data.get("username")
    password = data.get("password")
    token = make_token(username)
    if authenticate(username=username, password=password):
        return JsonResponse({"code": 200, "username": username, "data": {"token": token}})
    else:
        return JsonResponse({"code": 10200, "error": "请求错误"})
def make_token(username, expire=856400):
    payload = {
        "exp": int(time.time()) + expire,
        "username": username
    }
    key = settings.JWT_TOKEN_KEY
    return jwt.encode(payload, key, algorithm="HS256")

def avatar(request):
    token = request.META.get("HTTP_AUTHORIZATION")
    if not token:
        return JsonResponse({"code": 200, "data": {"is_logged_in": 0, "avatar": ""}})
    try:
        res = jwt.decode(token, settings.JWT_TOKEN_KEY, algorithms="HS256")
        username = res["username"]
        user = UserProfile.objects.get(username=username)
        avatar = str(user.avatar)
        return JsonResponse({"code": 200, "data": {"is_logged_in": 1, "username": username, "avatar": avatar}})
    except Exception as e:
        return JsonResponse({"code": 200, "data": {"is_logged_in": 0, "avatar": ""}})

